package com.ms.common.utils;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public final class SendMail {
	public static void sendEmail(String host, String username, String password,
			String isValate, String from, String to, String nickname,
			String subject, String context) throws Exception {



		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

		senderImpl.setHost(host);
		senderImpl.setUsername(username);
		senderImpl.setPassword(password);
		senderImpl.setPort(645);


		Properties pp = new Properties();
		pp.put("mail.smtp.auth", isValate);

		senderImpl.setJavaMailProperties(pp);

		SimpleMailMessage msg = new SimpleMailMessage();

		msg.setFrom(from);
		msg.setTo(to);
		msg.setSubject(subject);
		msg.setText(context);
		try {
			MimeMessage mimeMsg = senderImpl.createMimeMessage();

			MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true,
					"UTF-8");
			helper.setTo(msg.getTo());
			helper.setSubject(msg.getSubject());
			try {
				helper.setFrom(msg.getFrom(), nickname);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			helper.setText(msg.getText(), true);
			senderImpl.send(mimeMsg);
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}

	}

}
